<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
          header_list[e].value =
            header_list[e].type == 'input_number' ? ['', ''] : ''
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div class="c_666 fw">铝模平台价格管理</div>
        <div class="flex">
          <el-button
            type="primary"
            @click="add"
            v-if="has_role_list[3].has_role"
            >新增</el-button
          >

          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <myTable
        :data="list"
        :maxHeight="max_height"
        :height_size="height_size"
        :loading="loading"
        :header_list="header_list"
        @edit_list="edit_list"
      ></myTable>
      <el-pagination
        class="m_10_0 pagination"
        v-model:currentPage="form_data.current"
        v-model:page-size="form_data.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="
          (e) => {
            form_data.pageSize = e
            get_list()
          }
        "
        @current-change="
          (e) => {
            form_data.current = e
            get_list()
          }
        "
      />
    </div>
  </div>

  <el-drawer
    v-model="show_box"
    direction="rtl"
    @close="resetForm(addservicepriceform)"
    size="80%"
    :close-on-click-modal="false"
  >
    <template #title>
      <h4 v-if="is_exam">审核</h4>
      <div v-else>
        <h4 v-if="add_form_data.id == ''">新增服务价格申请</h4>
        <h4 v-else>编辑服务价格申请</h4>
      </div>
    </template>
    <template #default>
      <el-form
        :model="add_form_data"
        ref="addservicepriceform"
        label-width="100px"
        :rules="rules"
      >
        <div class="flex_wp" v-if="!is_exam">
          <el-form-item label="申请日期" prop="applyTime">
            <el-date-picker
              v-model="add_form_data.applyTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="x"
              placeholder="请选择申请日期"
            />
          </el-form-item>
          <el-form-item label="申请人">
            <el-input
              placeholder="申请人"
              disabled
              v-model="add_form_data.applyName"
            ></el-input>
          </el-form-item>
          <el-form-item label="启用日期" prop="enableTime">
            <el-date-picker
              v-model="add_form_data.enableTime"
              :disabled-date="disabledDate"
              format="YYYY-MM-DD"
              value-format="x"
              type="date"
              placeholder="请选择启用日期"
            />
          </el-form-item>
          <el-form-item label="备注" style="width: 100%">
            <el-input
              type="textarea"
              rows="4"
              placeholder="请输入备注"
              v-model="add_form_data.remark"
              show-word-limit
              maxlength="300"
            ></el-input>
          </el-form-item>
        </div>
        <div v-else>
          <div>
            <span style="color: #999999">申请日期：</span
            >{{ add_form_data.applyTime
            }}<span style="color: #999999; margin-left: 50px"
              >申请人：{{ add_form_data.applyName }}</span
            ><span style="color: #999999; margin-left: 50px">启用日期：</span
            >{{ add_form_data.enableTime }}
          </div>
          <div class="flex_start m_top10">
            <p style="color: #999999">备注：</p>
            <p>{{ add_form_data.remark }}</p>
          </div>
        </div>
        <div class="m_20_0">
          当前价格参考标准：<el-select
            v-model="box_current_id"
            @change="get_current_price()"
          >
            <el-option
              v-for="(item, index) in box_options"
              :key="index"
              :value="item.id"
              :label="formatDate(parseInt(item.applyTime), 'yyyy-MM-dd')"
            ></el-option>
          </el-select>
          申请并审核通过的调整后价格
        </div>
        <div class="">
          <el-table
            :data="project_list"
            style="text-align: center"
            border
            class="small_input"
          >
            <el-table-column
              label="序号"
              type="index"
              width="80px"
              fixed
            ></el-table-column>
            <el-table-column
              label="服务项目"
              prop="name"
              width="90px"
              fixed
            ></el-table-column>
            <el-table-column label="计价方式" prop="type" width="90px" fixed>
              <template #default="scope: any">
                <div v-for="item in dict_children_list">
                  <span v-show="scope.row?.type == item.dictCode">{{
                    item.dictValue
                  }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              v-for="(item, index) in enterprise_level_list"
              :key="index"
              :label="item.name"
            >
              <el-table-column label="当前价格" width="120px">
                <template #default="scope: any">
                  <div v-if="scope.row.current_price_list.length">
                    {{ scope.row.current_price_list[index] }}
                  </div>
                  <div v-else>--</div>
                </template>
              </el-table-column>
              <el-table-column label="调整后价格" width="120px">
                <template #default="scope: any">
                  <el-input
                    :disabled="is_exam"
                    placeholder="请输入"
                    @input="
                      scope.row.change_price_list[index] =
                        scope.row.change_price_list[index].replace(
                          /^(0+)|[^\d]+/g,
                          ''
                        )
                    "
                    v-model="scope.row.change_price_list[index]"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="赠送数量" width="90px">
                <template #default="scope: any">
                  <el-input
                    :disabled="is_exam"
                    placeholder="请输入"
                    v-model="scope.row.giftNum_list[index]"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="有限时长" width="200px">
                <template #default="scope: any">
                  <div class="flex">
                    <el-input
                      :disabled="is_exam"
                      placeholder="请输入"
                      v-model="scope.row.effectiveTime_list[index]"
                    ></el-input>
                    <el-select
                      v-model="scope.row.timeUnit_list[index]"
                      style="margin-left: 10px"
                      :disabled="is_exam"
                    >
                      <el-option
                        v-for="(item, index) in durctionTpye_list"
                        :key="index"
                        :label="item.dictValue"
                        :value="parseInt(item.dictCode)"
                      ></el-option>
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="使用后赠送数量" width="90px">
                <template #default="scope: any">
                  <el-input
                    :disabled="is_exam"
                    placeholder="请输入"
                    v-model="scope.row.useGiftNum_list[index]"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="使用后赠送-有限时长" width="200px">
                <template #default="scope: any">
                  <div class="flex">
                    <el-input
                      :disabled="is_exam"
                      placeholder="请输入"
                      v-model="scope.row.useEffectiveTime_list[index]"
                    ></el-input>
                    <el-select
                      v-model="scope.row.useTimeUnit_list[index]"
                      style="margin-left: 10px"
                      :disabled="is_exam"
                    >
                      <el-option
                        v-for="(item, index) in durctionTpye_list"
                        :key="index"
                        :label="item.dictValue"
                        :value="parseInt(item.dictCode)"
                      ></el-option>
                    </el-select>
                  </div>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="备注" width="200px">
              <template #default="scope: any">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="请输入"
                  :disabled="is_exam"
                >
                </el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="tr m_top20">
          <el-button @click="resetForm(addservicepriceform)">取消</el-button>
          <el-button
            type="primary"
            @click="submit(addservicepriceform)"
            v-if="!is_exam && add_form_data.status != '2'"
            >保存</el-button
          >
          <el-button
            type="primary"
            @click="exam_pass"
            v-if="is_exam && add_form_data.status == '1'"
            >审核</el-button
          >
        </div>
      </el-form>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import {
  check_role,
  formatDate,
  dictData,
  handle_search_key,
} from '@/utils/utils' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import myTable from '@/view/components/myTable.vue'
import { onMounted, ref, onUnmounted, nextTick, reactive } from 'vue'
import { FormInstance, ElMessage, ElMessageBox, FormRules } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { useStore } from 'vuex'
const addservicepriceform = ref<FormInstance>()
const rules = reactive<FormRules>({
  enableTime: [
    {
      required: true,
      type: 'date',
      message: '请选择启用日期',
      trigger: 'change',
    },
  ],
  applyTime: [
    {
      required: true,
      type: 'date',
      message: '请选择申请日期',
      trigger: 'change',
    },
  ],
})
const store = useStore()
const has_role_list = ref([
  { path: 'price/pass', has_role: false },
  { path: 'price/edit', has_role: false },
  { path: 'price/delete', has_role: false },
  { path: 'price/post', has_role: false },
  { path: 'price/info', has_role: false },
])
const max_height = ref()
nextTick(() => {
  max_height.value = window.innerHeight - 320 // 不带分页的 table 高度
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
})
const list = ref()
const total = ref()
const project_list = ref()
const loading = ref(false)
const show_box = ref(false)
const disabledDate = (time: Date) => {
  // 可选日期
  return time.getTime() < Date.now() - 3600 * 1000 * 24 * 1
}
const height_size = ref(1)
const header_list = ref<any>([
  {
    label: '申请单号',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
    prop: 'code',
  },
  {
    label: '申请日期',
    value: ['', ''],
    showTable: true,
    type: 'date',
    isShow: true,
    options: [],
    prop: 'applyTime',
    is_time_stamp: true,
  },
  {
    label: '申请人',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
    prop: 'applyManagerUserName',
  },
  {
    label: '新价格启用日期',
    value: ['', ''],
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
    prop: 'enableTime',
    is_time_stamp: true,
  },
  {
    label: '备注',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
    prop: 'remark',
    show_overflow_tooltip: true,
  },
])
const form_data = ref({
  current: 1,
  code: '',
  applicant: '',
  applyTime: '',
  enableTime: '',
  remark: '',
  pageSize: 10,
  status: '',
})
const add_form_data = ref({
  id: '',
  applicant: store.state.user_info.id,
  applyName: store.state.user_info.username,
  applyTime: formatDate(new Date(), 'yyyy-MM-dd'),
  enableTime: '',
  remark: '',
  servicePriceItemList: [],
  status: '',
})
const box_current_id = ref() //当前价格参考调整记录id
const box_options = ref()

const dict_children_list = ref()
const durctionTpye_list = ref()
onMounted(() => {
  EventBus.on('refresh', () => {
    get_list()
    get_project_list()
    get_enterprise_level_list()
    ElMessage.success('刷新成功！')
  })
  get_list()
  get_project_list()
  get_enterprise_level_list()
  dictData('1511538556160180226').then((res) => {
    dict_children_list.value = res as any
  }) // 获取字典值 计价模式
  dictData('1514912374253948929').then((res) => {
    durctionTpye_list.value = res as any
  }) // 获取字典值  // 时长类型
})
onUnmounted(() => {
  EventBus.off('refresh')
})

const add = () => {
  get_project_list()
  let data = JSON.parse(JSON.stringify(handle_search_key(form_data.value)))
  data.status.detailList[0].value = '2'
  add_form_data.value.applyName = store.state.user_info.username
  axios
    .request({
      url: serviceApi.servicePrice_list,
      method: 'post',
      data: data,
    })
    .then((res) => {
      console.log(res)
      box_options.value = res.data.content.length ? res.data.content : []
      if (res.data.content.length) {
        box_current_id.value = res.data.content[0].id
        get_current_price()
      }
      loading.value = false
      show_box.value = true
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const exam_pass = () => {
  ElMessageBox.confirm('确定审核通过该服务价格设置？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    closeOnClickModal: false,
    type: 'warning',
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.servicePrice_pass + '/' + add_form_data.value.id,
          method: 'put',
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('审核通过！')
          setTimeout(() => {
            show_box.value = false
            get_list()
          }, 1000)
        })
        .catch((error) => {
          ElMessage.error(error)
        })
    })
    .catch(() => {})
}
const submit = async (formEl: FormInstance | undefined) => {
  let has_change = false
  project_list.value.forEach((element) => {
    element.servicePriceItemDetailList = []
    if (element.change_price_list && element.change_price_list.length > 0) {
      has_change = true
    }
    for (let i in enterprise_level_list.value) {
      var a = {
        levelId: enterprise_level_list.value[i].id,
        price: element.change_price_list[i] ? element.change_price_list[i] : 0,
        giftNum: element.giftNum_list[i],
        effectiveTime: element.effectiveTime_list[i],
        timeUnit: element.timeUnit_list[i],
        useGiftNum: element.useGiftNum_list[i],
        useEffectiveTime: element.useEffectiveTime_list[i],
        useTimeUnit: element.useTimeUnit_list[i],
      }
      element.servicePriceItemDetailList.push(a)
    }
  })
  console.log(project_list.value)
  add_form_data.value.servicePriceItemList = project_list.value
  if (!has_change) {
    ElMessage.error('至少填写一项调整后价格！')
    return
  }
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      axios
        .request({
          url:
            add_form_data.value.id == ''
              ? serviceApi.servicePrice_crud
              : serviceApi.servicePrice_crud + '/' + add_form_data.value.id,
          method: add_form_data.value.id == '' ? 'post' : 'put',
          data: add_form_data.value,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！等待管理员审核...')
          setTimeout(() => {
            get_list()
            show_box.value = false
          }, 1000)
        })
        .catch((error) => {
          ElMessage.error(error)
        })
    }
  })
}
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.servicePrice_list,
      method: 'post',
      data: handle_search_key(form_data.value),
    })
    .then((res) => {
      res.data.content.forEach((i) => {
        i.btn_list = [
          {
            label: '审核',
            icon: 'table_pass',
            has_role: has_role_list.value[0].has_role,
            btn_show: i.status == 1,
          },
          {
            label: '编辑',
            icon: 'table_edit',
            has_role: has_role_list.value[1].has_role,
            btn_show: i.status == 1,
          },
          {
            label: '删除',
            icon: 'table_delete',
            has_role: has_role_list.value[2].has_role,
            btn_show: i.status == 1,
          },
          {
            label: '详情',
            icon: 'table_info',
            has_role: has_role_list.value[4].has_role,
            btn_show: i.status == 2,
          },
        ]
      })
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
      loading.value = false
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const get_project_list = () => {
  axios
    .request({
      url: serviceApi.project_list,
      method: 'post',
    })
    .then((res) => {
      res.data.forEach((element) => {
        element.itemId = element.id
        element.current_price_list = []
        element.change_price_list = []
        element.giftNum_list = []
        element.effectiveTime_list = []
        element.timeUnit_list = []

        element.useGiftNum_list = []
        element.useEffectiveTime_list = []
        element.useTimeUnit_list = []
        element.remark = ''
      })
      project_list.value = res.data
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const enterprise_level_list = ref()
const get_enterprise_level_list = () => {
  axios
    .request({
      url: serviceApi.enterprise_level_list,
      method: 'post',
    })
    .then((res) => {
      enterprise_level_list.value = res.data
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const is_exam = ref(false) // 是否为管理员审核

const edit_list = (e) => {
  if (e.type == 1) {
    ElMessageBox.confirm('确定审核通过该记录？', '', {
      closeOnClickModal: false,
      type: 'warning',
    })
      .then(() => {
        axios
          .request({
            url: serviceApi.servicePrice_pass + '/' + e.item.id,
            method: 'put',
          })
          .then((res) => {
            console.log(res)
            ElMessage.success('操作成功！')
            setTimeout(() => {
              get_list()
            }, 1000)
          })
          .catch((error) => {
            ElMessage.error(error)
          })
      })
      .catch(() => {})
  } else if (e.type == 2) {
    update_list(e.item)
  } else if (e.type == 4) {
    is_exam.value = true
    update_list(e.item)
  } else {
    ElMessageBox.confirm('确定删除该记录？', '', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      type: 'warning',
    })
      .then(() => {
        axios
          .request({
            url: serviceApi.servicePrice_crud + '/' + e.item.id,
            method: 'delete',
          })
          .then((res) => {
            console.log(res)
            ElMessage.success('操作成功！')
            setTimeout(() => {
              get_list()
            }, 1000)
          })
          .catch((error) => {
            ElMessage.error(error)
          })
      })
      .catch(() => {})
  }
}
const update_list = (e) => {
  add()
  axios
    .request({
      url: serviceApi.servicePrice_crud + '/' + e.id,
      method: 'get',
    })
    .then((res) => {
      add_form_data.value = {
        id: res.data.id,
        applicant: res.data.applyManagerUserInfo.id,
        applyName: res.data.applyManagerUserInfo.name,
        applyTime: formatDate(parseInt(res.data.applyTime), 'yyyy-MM-dd'),
        enableTime: formatDate(parseInt(res.data.enableTime), 'yyyy-MM-dd'),
        remark: res.data.remark,
        servicePriceItemList: [],
        status: res.data.status,
      }
      var list = res.data.servicePriceItemList
      var obj = enterprise_level_list.value
      console.log(obj)
      for (let i in list) {
        project_list.value.some((item) => {
          if (
            item.id == list[i].itemId &&
            list[i].servicePriceItemDetailList.length
          ) {
            item.remark = list[i].remark
            item.itemId = list[i].itemId
            for (let ii in list[i].servicePriceItemDetailList) {
              obj.some((item1) => {
                if (
                  item1.id == list[i].servicePriceItemDetailList[ii].levelId
                ) {
                  // 调整价格
                  item.change_price_list.push(
                    list[i].servicePriceItemDetailList[ii].price === null
                      ? ''
                      : list[i].servicePriceItemDetailList[ii].price
                  )
                  // 赠送数量
                  item.giftNum_list.push(
                    list[i].servicePriceItemDetailList[ii].giftNum === null
                      ? ''
                      : list[i].servicePriceItemDetailList[ii].giftNum
                  )
                  // 有效时长
                  item.effectiveTime_list.push(
                    list[i].servicePriceItemDetailList[ii].effectiveTime ===
                      null
                      ? ''
                      : list[i].servicePriceItemDetailList[ii].effectiveTime
                  )
                  // 时长单位
                  item.timeUnit_list.push(
                    list[i].servicePriceItemDetailList[ii].timeUnit === null
                      ? ''
                      : list[i].servicePriceItemDetailList[ii].timeUnit
                  )
                  // 使用后赠送数量
                  item.useGiftNum_list.push(
                    list[i].servicePriceItemDetailList[ii].useGiftNum === null
                      ? ''
                      : list[i].servicePriceItemDetailList[ii].useGiftNum
                  )
                  // 使用后有效时长
                  item.useEffectiveTime_list.push(
                    list[i].servicePriceItemDetailList[ii].useEffectiveTime ===
                      null
                      ? ''
                      : list[i].servicePriceItemDetailList[ii].useEffectiveTime
                  )
                  // 使用后有效时长单位
                  item.useTimeUnit_list.push(
                    list[i].servicePriceItemDetailList[ii].useTimeUnit === null
                      ? ''
                      : list[i].servicePriceItemDetailList[ii].useTimeUnit
                  )
                }
              })
            }
          }
        })
      }
      console.log(project_list.value)
      show_box.value = true
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const get_current_price = () => {
  axios
    .request({
      url: serviceApi.servicePrice_crud + '/' + box_current_id.value,
      method: 'get',
    })
    .then((res) => {
      console.log(res, enterprise_level_list.value)
      if (res.data.servicePriceItemList.length) {
        var list = res.data.servicePriceItemList
        var obj = enterprise_level_list.value
        for (let i in list) {
          project_list.value.some((item) => {
            if (
              item.id == list[i].itemId &&
              list[i].servicePriceItemDetailList.length
            ) {
              item.current_price_list = []
              for (let ii in list[i].servicePriceItemDetailList) {
                obj.some((item1) => {
                  if (
                    item1.id == list[i].servicePriceItemDetailList[ii].levelId
                  ) {
                    item.current_price_list.push(
                      // 当前价格
                      list[i].servicePriceItemDetailList[ii].price
                    )
                  }
                  return (
                    item1.id == list[i].servicePriceItemDetailList[ii].levelId
                  )
                })
              }
            }
          })
        }
      }
      console.log(project_list.value)
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const search_key = () => {
  form_data.value = {
    current: 1,
    code: header_list.value[0].value,
    applyTime: header_list.value[1].value,
    applicant: header_list.value[2].value,
    enableTime: header_list.value[3].value,
    remark: header_list.value[4].value,
    pageSize: 10,
    status: '',
  }
  get_list()
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    applicant: store.state.user_info.id,
    applyName: '',
    applyTime: formatDate(new Date(), 'yyyy-MM-dd'),
    enableTime: '',
    remark: '',
    servicePriceItemList: [],
    status: '',
  }
  form_data.value.status = ''
  is_exam.value = false
  show_box.value = false
}
</script>

<style lang="scss" scoped>
.small_input {
  :deep(.el-input__inner) {
    padding-right: 11px !important;
  }
}
.el-form-item {
  width: 33%;
}
</style>
